package com.wk.wms.listener;

import com.alibaba.fastjson.JSON;
import com.wk.common.constant.RedisKey;
import com.wk.common.constant.mq.ItemExchange;
import com.wk.common.constant.mq.ItemQueue;
import com.wk.common.constant.mq.ItemRoutingKey;
import com.wk.wms.mapper.WareSkuMapper;
import com.wk.wms.vo.SkuLockVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听库存解锁操作
 */
@Component
public class StockListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private WareSkuMapper wareSkuMapper;

    /**
     * 订单支付成功 减少商品库存
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = ItemExchange.ORDER_EXCHANGE, ignoreDeclarationExceptions = "true"),
            value = @Queue(value = ItemQueue.STOCK_DECREASE_QUEUE, durable = "true"),
            key = ItemRoutingKey.STOCK_DECREASE
    ))
    public void stockDecrease(String orderToken){

        //从Redis中获取订单编号对应已锁定的商品信息
        String skuLockVoJson = redisTemplate.boundValueOps(RedisKey.STOCK_LOCK + orderToken).get();

        if (StringUtils.isNotBlank(skuLockVoJson)) {
            List<SkuLockVO> skuLockVOS = JSON.parseArray(skuLockVoJson, SkuLockVO.class);

            //解锁订单创建失败 但锁定成功的商品库存
            skuLockVOS.forEach(skuLockVO -> wareSkuMapper.decreaseStock(skuLockVO));

            //删除已锁定的库存信息
            redisTemplate.delete(RedisKey.STOCK_LOCK + orderToken);
        }
    }


    /**
     * 解锁订单创建失败 但锁定成功的商品库存
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = ItemExchange.ORDER_EXCHANGE, ignoreDeclarationExceptions = "true"),
            value = @Queue(value = ItemQueue.STOCK_UNLOCK_QUEUE, durable = "true"),
            key = ItemRoutingKey.STOCK_UNLOCK
    ))
    public void stockUnlock(String orderToken) {

        //从Redis中获取订单编号对应已锁定的商品信息
        String skuLockVoJson = redisTemplate.boundValueOps(RedisKey.STOCK_LOCK + orderToken).get();

        if (StringUtils.isNotBlank(skuLockVoJson)) {
            List<SkuLockVO> skuLockVOS = JSON.parseArray(skuLockVoJson, SkuLockVO.class);

            //解锁订单创建失败 但锁定成功的商品库存
            skuLockVOS.forEach(skuLockVO -> wareSkuMapper.unLockStock(skuLockVO));

            //删除已锁定的库存信息
            redisTemplate.delete(RedisKey.STOCK_LOCK + orderToken);
        }
    }

}
